#-*- coding: utf-8 -*-
import kyMD5
import os
import sys
import sqlite3
#input path a sync to b
#copy files in a to b 
#copy files in a to b and del file in a
    
# work flow
#  calc file md5 in b and insert to db for query
#  start walk file in a

if len(sys.argv)> 1:
    workDir = os.walk(sys.argv[1])
    #print type(sys.argv[1])
    conn = sqlite3.connect("data.db")
    conn.text_factory = str
    c = conn.cursor();
    c.execute("select count(*) from sqlite_master")
    cnt = c.fetchone()[0]
    #print cnt
    if cnt == 0 :
        c.execute("create table fileTbl(finename TEXT,filePath TEXT,MD5 TEXT)")
    for ftube in workDir:
        for filename in ftube[2]: 
            fullname = ftube[0] + "\\" + filename
            fileMd5 = kyMD5.md5sum(fullname)
            c.execute("select count(*) from fileTbl where filePath='" + fullname +"'")
            cnt = c.fetchone()[0]
            print cnt ," file : ", fullname , " MD5 :" , fileMd5
            if cnt == 0:
                c.execute("insert into fileTbl values(?,?,?)",(filename,fullname,fileMd5))
    conn.commit()
    #c.execute("select * from fileTbl where MD5 =(select MD5  from fileTbl  group by MD5 having count(MD5) > 1)")
    c.execute("select * from fileTbl where MD5 in (select MD5 from fileTbl  group by MD5 having count(MD5) > 1) order by MD5")  
    print "======================== result ========================"
    oldMd5 = ""
    for r in c:
        
        if  oldMd5 != r[2]:
            if oldMd5 == "":
                oldMd5 = r[2]
            else:
                oldMd5 = r[2]
                print "\r\n"
        print r[1],r[2]
    c.close()        
else:
    print "Give Dir Path!!\r\n"
